<?php
namespace app\job;

use app\api\controller\v1\Clue as ClueModel;
use think\Db;
use think\Exception;
use think\Queue;
use think\queue\Job;

//php think queue:listen --queue ClueAllLossPrice
//第五步线索池累加剩余成本
class ClueAllLossPrice{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data){
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $job->delete();
                // 也可以重新发布这个任务
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }


    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function doHelloJob($data) {
        try {
            $dateTime=date('Y-m-d',$data['time'][1][0]);
            $map['a.time']=$dateTime;
            $map['a.clue_num']=['=',0];
            $map['a.is_cost']=['=',0];

            $map3['a.create_time'] = $data['time'];

            $total=model('ClueCostLog')->alias('a')->field('sum(true_consume) true_consume,sum(money) money')->where($map)->find();
            $totalPrice=!empty($total['money'])?$total['money']:0;
            $totalTruePrice=!empty($total['true_consume'])?$total['true_consume']:0;
//            dump($total);
            $total=model('Clue')->alias('a')->field('count(id) num,sum(xz_price) xz_price,sum(xz_true_price) xz_true_price,sum(xz_price2) xz_price2,sum(xz_true_price2) xz_true_price2')->where($map3)->find();
            $allXzPirce=!empty($total['xz_price'])?$total['xz_price']:0;
            $allXzTruePirce=!empty($total['xz_true_price'])?$total['xz_true_price']:0;
            $allXzPirce2=!empty($total['xz_price2'])?$total['xz_price2']:0;
            $allXzTruePirce2=!empty($total['xz_true_price2'])?$total['xz_true_price2']:0;
            $clueNum=!empty($total['num'])?$total['num']:0;


//            dump($total);


            $list=model('Clue')->alias('a')
                ->where($map3)->chunk(20,function($users) use ($totalPrice,$totalTruePrice,$allXzPirce,$allXzTruePirce,$allXzPirce2,$allXzTruePirce2,$clueNum) {
                    $log=[];
                    foreach ($users as $val) {
                        //金额占比
                        $inserDataLog['clue_id']=$val['id'];
                        $inserDataLog['type']=5;
                        $inserDataLog['create_time']=time();
                        $inserDataLog['clue_time']=strtotime($val['create_time']);
                        $inserDataLog['xz_type']=1;
                        if($val['xz_price']>0){
                            $rate1=bcdiv($val['xz_price'],$allXzPirce,6);
                            $price=round(bcmul($totalPrice,$rate1,6),2);
                        }else{
                            if($allXzPirce==0&&$clueNum>0){
                                $price=round(bcdiv($totalPrice,$clueNum,6),2);
                            }else{
                                $price=0;
                            }
                        }
                        $inserDataLog['price']=$price;
                        if($val['xz_true_price']>0){
                            $rate2=bcdiv($val['xz_true_price'],$allXzTruePirce,6);
                            $true_price=round(bcmul($totalTruePrice,$rate2,6),2);
                        }else{
                            if($allXzTruePirce==0&&$clueNum>0){
                                $true_price=round(bcdiv($totalTruePrice,$clueNum,6),2);
                            }else{
                                $true_price=0;
                            }

                        }
                        $inserDataLog['true_price']=$true_price;

                        if($price>0||$true_price>0){
                            $log[]=$inserDataLog;
                        }
                        //修改LOG2
                        $inserDataLog['xz_type']=2;
                        if($val['xz_price2']>0){
                            $rate1=bcdiv($val['xz_price2'],$allXzPirce2,6);
                            $price2=round(bcmul($totalPrice,$rate1,6),2);
                        }else{
                            if($allXzPirce2==0&&$clueNum>0){
                                $price2=round(bcdiv($totalPrice,$clueNum,6),2);
                            }else{
                                $price2=0;
                            }
                        }
                        $inserDataLog['price']=$price2;
                        if($val['xz_true_price2']>0){
                            $rate2=bcdiv($val['xz_true_price2'],$allXzTruePirce2,6);
                            $true_price2=round(bcmul($totalTruePrice,$rate2,6),2);
                        }else{
                            if($allXzTruePirce2==0&&$clueNum>0){
                                $true_price2=round(bcdiv($totalTruePrice,$clueNum,6),2);
                            }else{
                                $true_price2=0;
                            }
                        }
                        $inserDataLog['true_price']=$true_price2;
                        if($price2>0||$true_price2>0){
                            $log[]=$inserDataLog;
                        }

                        if($price>0||$true_price>0||$price2>0||$true_price2>0){
                            Db::name('clue')->where('id',$val['id'])->inc('xz_price',$price)->inc('xz_true_price',$true_price)->inc('xz_price2',$price2)->inc('xz_true_price2',$true_price2)->update();
                        }

                    }
                    if(!empty($log)){
                        Db::name('clue_zero_cost_details')->insertAll($log);
                    }
                });
            echo json_encode($data,JSON_UNESCAPED_UNICODE);
            return true;
        }catch (Exception $e){
            $errData=[
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage(),
                'flie'=>$e->getFile(),
                'line'=>$e->getLine(),
            ];
            trace($errData,'error');
            return true;
        }
    }

}